package br.ufal.ic.dao.mock;

import br.ufal.ic.core.Delegate;
import br.ufal.ic.dao.DelegateDAO;
import java.util.*;

/**
 * DAO mock para testes sem persitencia de dados dos delegados.
 * 
 * @author Marcos Paulo
 */
public class MockDelegateDAO implements DelegateDAO {

    private Map<String, Delegate> delegates;

    public MockDelegateDAO() {
        delegates = new HashMap<String, Delegate>();
    }

    public MockDelegateDAO(Set<Delegate> delegates) {
        this();

        initDelegates(delegates);
    }

    private void initDelegates(Set<Delegate> delegates) {
        for (Delegate delegate : delegates) {
            save(delegate);
        }
    }

    public Delegate findByName(String name) {

        for (Delegate delegate : delegates.values()) {
            if (delegate.getInformation().getName().equals(name)) {
                return delegate;
            }
        }

        return null;
    }

    public void save(Delegate delegate) {

        if (delegate == null) {
            throw new IllegalArgumentException("informe um delegado a ser salvo.");
        }

        if (delegates.containsValue(delegate)) {
            throw new RuntimeException("delegado ja salvo.");
        }

        delegates.put(delegate.getId(), delegate);
    }

    public void delete(Delegate delegate) {
        if (delegates.remove(delegate.getId()) == null) {
            throw new RuntimeException("delegado não salvo: "
                    + delegate.getInformation().getName());
        }
    }

    public void update(Delegate delegate) {
        delete(delegate);
        save(delegate);
    }

    public List<Delegate> findAll() {
        return new ArrayList<Delegate>(delegates.values());
    }

    public Delegate findById(String id) {
        return delegates.get(id);
    }
}
